#!/bin/bash
# possible distlist values are: debian ubuntu
# several values possible, separated by one whitespace
distlist="debian"

ubuntuarchlist=""
debianarchlist="x86_64"

debianmirror="ftp.halifax.rwth-aachen.de::debian/dists"
debianverlist="stable"
debianbaselist='$ver/main/installer-$arch/current/images/netboot/debian-installer/$arch/linux $ver/main/installer-$arch/current/images/netboot/debian-installer/$arch/initrd.gz'

ubuntumirror="ftp.halifax.rwth-aachen.de::ubuntu/dists"
# several releases possible, separated by one whitespace
ubuntuverlist=""
ubuntubaselist='$ver/main/installer-$arch/current/images/netboot/ubuntu-installer/$arch/linux $ver/main/installer-$arch/current/images/netboot/ubuntu-installer/$arch/initrd.gz'

local=/var/lib/tftpboot/img

function genverlist ()
# function genverlist
{
if [ "$dist" == "debian" ]; then
  verlist="$debianverlist"
elif [ "$dist" == "ubuntu" ]; then
  verlist="$ubuntuverlist"
fi
}

function genarchlist ()
# function genarchlist
{
if [ "$dist" == "debian" ]; then
  archlist="$debianarchlist" 
elif [ "$dist" == "ubuntu" ]; then
  archlist="$ubuntuarchlist"
fi
}

function genbaselist ()
{
if [ "$dist" == "debian" ]; then
   baselist=`eval echo $debianbaselist`
elif [ "$dist" == "ubuntu" ]; then
   baselist=`eval echo $ubuntubaselist`
fi
}

function genrsync ()
{
target="$local/$dist/$ver/$arch"

if [ "$dist" == "debian" ]; then
  if [[ $arch = i*86 ]]; then
    target="$local/$dist/$ver/x86"
  elif [[ $arch = x86_64 ]]; then
    base=$(echo $base | sed "s;$arch;amd64;g")
    target="$local/$dist/$ver/x86_64"
  fi

 mirror="$debianmirror"
 remote="$mirror/$base"

elif [ "$dist" == "ubuntu" ]; then
  if [[ $arch = i*86 ]]; then
    target="$local/$dist/$ver/x86"
  elif [[ $arch = x86_64 ]]; then
    base=$(echo $base | sed "s;$arch;amd64;g")
    target="$local/$dist/$ver/x86_64"
  fi

 mirror="$ubuntumirror"
 remote="$mirror/$base"
fi

[ ! -d "$target" ] && /bin/mkdir -p "$target"

/bin/echo $remote $target
/usr/bin/rsync $rsyncparams "$remote" "$target"

if [ "$dist" == "debian" ]; then
  [ -f $target/initrd.gz.orig ] || cp -p $target/initrd.gz $target/initrd.gz.orig
  [ -f $local/$dist/$ver/firmware.cpio.gz ] || wget http://cdimage.debian.org/cdimage/unofficial/non-free/firmware/stable/current/firmware.cpio.gz -O $local/$dist/$ver/firmware.cpio.gz
  cat $target/initrd.gz.orig $local/$dist/$ver/firmware.cpio.gz > $target/initrd.gz
fi
}

function fixperms ()
{
/bin/echo "fixing permissions"
find $local/$dist -type f -exec chmod 664 {} \;
find $local/$dist -type d -exec chmod 775 {} \;
}

for dist in $distlist; do
  echo $dist
  genverlist 
  for ver in $verlist; do
    genarchlist
    for arch in $archlist; do
      genbaselist
      for base in $baselist; do
        genrsync
      done
    done
  done
done
fixperms
